package com.example.personblog.service;

import com.example.personblog.common.ResultEnum;
import com.example.personblog.entity.dto.LoginRequest;
import com.example.personblog.entity.dto.RegisterRequest;
import com.example.personblog.entity.User;
import com.example.personblog.exception.BusinessException;
import com.example.personblog.repository.UserRepository;
import com.example.personblog.utils.JwtUtil;
import com.example.personblog.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private JwtUtil jwtUtil;

    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    public User getUserById(Long id) {
        return userRepository.findById(id)
                .orElseThrow(() -> new BusinessException(ResultEnum.USER_NOT_EXIST));
    }

    public User createUser(User user) {
        if (userRepository.existsByUsername(user.getUsername())) {
            throw new BusinessException(ResultEnum.USER_ALREADY_EXIST);
        }
        return userRepository.save(user);
    }

    public User updateUser(User user) {
        if (!userRepository.existsById(user.getId())) {
            throw new BusinessException(ResultEnum.USER_NOT_EXIST);
        }
        return userRepository.save(user);
    }

    public void deleteUser(Long id) {
        if (!userRepository.existsById(id)) {
            throw new BusinessException(ResultEnum.USER_NOT_EXIST);
        }
        userRepository.deleteById(id);
    }

    public Map<String, Object> login(LoginRequest loginRequest) {
        User user = userRepository.findByUsername(loginRequest.getUsername());
        if (user == null || !MD5Util.verify(loginRequest.getPassword(), user.getSalt(), user.getPassword())) {
            throw new BusinessException(ResultEnum.USER_LOGIN_FAILED);
        }

        // 生成访问令牌和刷新令牌
        String accessToken = jwtUtil.generateAccessToken(user);

        // 更新最后登录时间
        user.setLastLoginTime(new Date());
        userRepository.save(user);

        // 返回用户信息和令牌
        Map<String, Object> result = new HashMap<>();
        result.put("accessToken", accessToken);
        result.put("user", user);
        return result;
    }

    public User register(RegisterRequest registerRequest) {
        if (userRepository.existsByUsername(registerRequest.getUsername())) {
            throw new BusinessException(ResultEnum.USER_ALREADY_EXIST);
        }

        // 生成盐值并加密密码
        String salt = MD5Util.generateSalt();
        String encryptedPassword = MD5Util.encrypt(registerRequest.getPassword(), salt);

        User user = new User();
        user.setUsername(registerRequest.getUsername());
        user.setPassword(encryptedPassword);
        user.setSalt(salt);
        user.setEmail(registerRequest.getEmail());
        user.setNickname(registerRequest.getNickname());
        user.setCreateTime(new Date());

        return userRepository.save(user);
    }
}